import config from '../config/main';
import Redis from 'ioredis';
import RedisReceiver from '../modules/RedisReceiver';

const redisStore = {};

function middleware(_app) {
    const app = _app;
    const log = app.log.getLogger('[redism]');

    const conn = new Redis(config.redis.port, config.redis.host);

    conn.on('ready', () => {
        log.info('connect redis success...');
    });

    conn.on('error', (e) => {
        log.info('connect redis fail %s', e);
    });

    const receiver = new RedisReceiver(app);
    const redisTask = new Redis(
        config.redis.port, config.redis.host, { db: config.redisdb.receive });

    // 订阅事件
    redisTask.subscribe(`__keyevent@${config.redisdb.receive}__:expired`);
    // 监听事件
    redisTask.on('message', (subKey, content) => {
        if (!content) {
            this.log.warn(`reids onMessage ${subKey} error, content: ${content}`);
        } else {
            const contents = content.split('##');
            const channel = contents[0];
            const message = contents[1];
            receiver.onMessage(channel, message);
        }
    });
    log.info('redis subscribe success');

    const redis = (db) => {
        let redisConn = redisStore[db];
        if (!redisConn) {
            redisConn = new Redis(config.redis.port, config.redis.host, { db });
            redisStore[db] = redisConn;
        }
        return redisConn;
    };

    const expireTask = (channel, message, expire) => {
        // 设置任务
        redis(config.redisdb.receive).setex(`${channel}##${message}`, expire, 'ok');
    };

    redis.expireTask = expireTask;
    app.redis = redis;
    // app.redisBackend = redisBackend;

    return function* dispatch(next) {
        this.redis = redis;
        yield next;
    };
}

export default middleware;
